<?php
namespace app\api\controller;

use app\api\model\Cart as CartModel;
use app\api\model\Goods;
use app\api\model\ModeOrders;
use app\api\model\ModeProduct;
use app\api\model\UserAddress;
use think\Request;

class Cart extends Base
{
    // 是否自动实例化当前模型
    protected $autoNewModel = false;
    // 是否开启自动验证
    protected $autoValidateCheck = false;


    public function add()
    {
        //获取商品ID
        $goods_id = (int)request()->param('goods_id', 0);
        //查询商品信息
        if (!$goods_info = Goods::findOrEmpty($goods_id)->toArray()) {
            //返回失败
            return showError('商品信息不存在');
        }
        //获取用户ID
        $user_id = (int)request()->UserModel->id;
        //判断购物车是否已存在当前数据
        if ($cart_id = (int)CartModel::where(compact('goods_id', 'user_id'))->value('id')) {
            //更新数据
            CartModel::where(compact('goods_id', 'user_id'))->update(['goods_num' => 1]);
        } else {
            //新增购物车数据
            $cart_id = CartModel::insertGetId([
                'user_id' => $user_id,
                'goods_id' => $goods_id,
                'goods_num' => 1,

                'sku_id' => 0,
                'merchants_id' => 0
            ]);
        }
        //返回信息
        return showSuccess(['ids' => $cart_id]);
    }


    public function information(Request $request)
    {
        //获取用户ID
        $user_id = (int)$request->UserModel->id;
        //整理结算信息
        $settlements = $amounts = [];
        //查询购物车信息
        if ($carts = CartModel::where('user_id', $user_id)->where('type', 1)->select()->toArray()) {
            //循环购物车信息
            foreach ($carts as $k => $cart) {
                //获取商品信息
                if (!$goods_info = Goods::field('cover, name, sale_amount')->append(['title'])->findOrEmpty($cart['goods_id'])->toArray()) {
                    //跳出循环
                    continue;
                }
                //整理金额
                $goods_info['amount'] = (float)$goods_info['sale_amount'];//(int)((float)$goods_info['price'] * 100);
                $goods_info['price'] = (int)((float)$goods_info['sale_amount']);
                //查询商品基本信息
                $carts[$k] = array_merge($cart, $goods_info);
                //设置追加信息
                $settlements[(int)$cart['id']] = (int)$cart['goods_num'];
                $amounts[(int)$cart['id']] = (int)$goods_info['amount'];
            }
        }
        //返回成功
        return showSuccess(['lists' => $carts, 'settlements' => $settlements, 'amounts' => $amounts]);
    }

    public function number(Request $request)
    {
        //获取用户ID
        $user_id = (int)$request->UserModel->id;
        //获取购物车ID
        $id = $cart_id = (int)$request->param('id', 0);
        $number = (int)$request->param('number', 0);

        //判断数据是否存在
        if (!$cart_info = CartModel::where(compact('id', 'user_id'))->findOrEmpty()->toArray()) {
            //返回失败
            return showError('购物车信息不存在');
        }

        if((int)$cart_info['type'] === 2){
            if (!$goods_info = ModeProduct::findOrEmpty($cart_info['goods_id'])->toArray()) {
                //返回失败
                return showError('商品信息不存在');
            }
            if((int)$goods_info['type'] === 2) {
                return showError('库存不足');
            }
            if((int)$goods_info['type'] === 3) {
                return showError('库存不足');

                $count = (int)ModeOrders::where('user_id', $user_id)
                    ->where('status', 'payed')
                    ->where('type', 3)
                    ->sum('num');
                if(($count + $number) > 5){
                    return showError('每人最多购买5股');
                }
            }
        }

        //判断数量
        if ($number <= 0) {
            //删除谁
            CartModel::where('id', $id)->delete();
        } else {
            //更新数据
            CartModel::where('id', $id)->update(['goods_num' => $number]);
        }
        //返回成功
        return showSuccess(compact('cart_id',  'number'));
    }

    public function settlementInformation()
    {
        //获取用户ID
        $user_id = (int)request()->UserModel->id;
        $user_level_id = (int)request()->UserModel->virtual_level_id;
        //获取购物车ID
        $cart_id = $id = (int)request()->param('ids', 0);
        //判断数据是否存在
        if (!$cart_info = CartModel::where(compact('id', 'user_id'))->findOrEmpty()->toArray()) {
            //返回失败
            return showError('购物车信息不存在');
        }
        //查询商品信息
        $goods_info = Goods::where('id', (int)$cart_info['goods_id'])->findOrEmpty()->toArray();
        //判断是否存在指定地址
        if (!$user_address_id = (int)request()->param('address_id', 0)) {
            //查询默认信息
            $user_address_id = (int)UserAddress::where('user_id', $user_id)->order('is_default', 'desc')->order('create_time', 'desc')->value('id');
        }
        //查询地址信息
        $address_info = $user_address_id > 0 ? UserAddress::where('id', $user_address_id)->field(['id', 'phone', 'consignee', 'province_name', 'city_name', 'area_name', 'address', 'province_id', 'city_id', 'area_id'])->findOrEmpty()->toArray() : [];
        //整理全部金额
        $express_amount = 0;
        //整理总商品金额
        $goods_amount = bcmul((string)$goods_info['sale_amount'], (string)$cart_info['goods_num']);
        $goods_amount_key = 'sale_amount';
        if($user_level_id > 0)
        {
            $goods_amount_key = $user_level_id > 5 ? 'sale_amount5' : 'sale_amount' . $user_level_id;
        }
        $discount_amount = bcmul(bcsub($goods_info['sale_amount'], $goods_info[$goods_amount_key]), $cart_info['goods_num']);
        //默认显示地址
        $address_enable = true;
        //整理优惠信息
        $discounts = [];

        //TODO ：根据商品分区判断是否需要开启地址显示

        //TODO : 根据商品分区判断显示抵扣项目

        //TODO : 根据商品情况判断是否存在物流费用


        //整理数据
        $data = [
            'address' => [
                'enable' => $address_enable,
                'contents' => [
                    'enable' => $user_address_id > 0,
                    'address' => $address_info,
                ],
            ],
            'goods' => [['cover' => $goods_info['cover'], 'title' => $goods_info['name'], 'specification_name' => '默认', 'price' => $goods_info['sale_amount'], 'count' => $cart_info['goods_num']]],
            'discounts' => [
                'enable' => false,//!empty($discounts),
                'lists' => $discounts
            ],
            'amounts'=>[
                'goods_amount'=> $goods_amount,
                'express_amount'=> $express_amount,
                'discount_amount' => $discount_amount,
                'pay_amount'=> bcadd((string)$express_amount, bcsub((string)$goods_amount, (string)$discount_amount)),
            ]
        ];
        //显示数据
        return showSuccess($data);
    }

    public function modeAdd()
    {
        //获取商品ID
        $goods_id = (int)(request()->param('goods_id', 0));
        //查询商品信息
        if (!$goods_info = ModeProduct::findOrEmpty($goods_id)->toArray()) {
            //返回失败
            return showError('商品信息不存在');
        }

        //获取用户ID
        $user_id = (int)request()->UserModel->id;
        if((int)$goods_info['type'] === 2) {
            return showError('库存不足');
        }

        if((int)$goods_info['type'] === 3) {
            $count = (int)ModeOrders::where('user_id', $user_id)
                ->where('status', 'payed')
                ->where('type', 3)
                ->sum('num');
            if(($count + 1) > 5){
                return showError('每人最多购买5股');
            }
        }

        //判断购物车是否已存在当前数据
        if ($cart_id = (int)CartModel::where(compact('goods_id', 'user_id'))->where('type', 2)->value('id')) {
            //更新数据
            CartModel::where(compact('goods_id', 'user_id'))->update(['goods_num' => 1]);
        } else {
            //新增购物车数据
            $cart_id = CartModel::insertGetId([
                'user_id' => $user_id,
                'goods_id' => $goods_id,
                'goods_num' => 1,
                'type'=>2,
                'sku_id' => 0,
                'merchants_id' => 0
            ]);
        }
        //返回信息
        return showSuccess(['ids' => $cart_id]);
    }

    public function modeInformation()
    {
        //获取用户ID
        $user_id = (int)request()->UserModel->id;
        $ids = request()->param('ids', 0);
        //整理结算信息
        $settlements = $amounts = [];
        //查询购物车信息
        if ($carts = CartModel::where('user_id', $user_id)->where('type', 2)->where('id', $ids)->select()->toArray()) {
            //循环购物车信息
            foreach ($carts as $k => $cart) {
                //获取商品信息
                if (!$goods_info = ModeProduct::field('img, title, price')
                    ->append(['cover'])
                    ->findOrEmpty($cart['goods_id'])->toArray()) {
                    //跳出循环
                    continue;
                }
                //整理金额
                $goods_info['amount'] = (float)$goods_info['price'];//(int)((float)$goods_info['price'] * 100);
                //查询商品基本信息
                $carts[$k] = array_merge($cart, $goods_info);
                //设置追加信息
                $settlements[(int)$cart['id']] = (int)$cart['goods_num'];
                $amounts[(int)$cart['id']] = (int)$goods_info['amount'];
            }
        }
        //返回成功
        return showSuccess(['lists' => $carts, 'settlements' => $settlements, 'amounts' => $amounts]);
    }
    public function modeSettlementInformation()
    {
        //获取用户ID
        $user_id = (int)request()->UserModel->id;
        //获取购物车ID
        $cart_id = $id = (int)request()->param('ids', 0);
        //判断数据是否存在
        if (!$cart_info = CartModel::where(compact('id', 'user_id'))->findOrEmpty()->toArray()) {
            //返回失败
            return showError('购物车信息不存在');
        }
        //查询商品信息
        $goods_info = ModeProduct::where('id', (int)$cart_info['goods_id'])->append(['cover'])->findOrEmpty()->toArray();

        if((int)$goods_info['type'] === 2 || (int)$goods_info['type'] === 3) {
            return showError('库存不足');
        }

        if((int)$goods_info['type'] === 3) {
            $count = (int)ModeOrders::where('user_id', $user_id)
                ->where('status', 'payed')
                ->where('type', 3)
                ->sum('num');
            if(($count + $cart_info['goods_num']) > 5){
                return showError('每人最多购买5股');
            }
        }
        //判断是否存在指定地址
//        if (!$user_address_id = (int)request()->param('address_id', 0)) {
//            //查询默认信息
//            $user_address_id = (int)UserAddress::where('user_id', $user_id)->order('is_default', 'desc')->order('create_time', 'desc')->value('id');
//        }
        //查询地址信息
//        $address_info = $user_address_id > 0 ? UserAddress::where('id', $user_address_id)->field(['id', 'phone', 'consignee', 'province_name', 'city_name', 'area_name', 'address', 'province_id', 'city_id', 'area_id'])->findOrEmpty()->toArray() : [];
        //整理全部金额
        $express_amount = $discount_amount = 0;
        //整理总商品金额
        $goods_amount = (float)bcmul((string)$goods_info['price'], (string)$cart_info['goods_num'], 2);
        //默认显示地址
        $address_enable = true;
        //整理优惠信息
        $discounts = [];

        //TODO ：根据商品分区判断是否需要开启地址显示

        //TODO : 根据商品分区判断显示抵扣项目

        //TODO : 根据商品情况判断是否存在物流费用


        //整理数据
        $data = [
//            'address' => [
//                'enable' => $address_enable,
//                'contents' => [
//                    'enable' => $user_address_id > 0,
//                    'address' => $address_info,
//                ],
//            ],
            'goods' => [['cover' => $goods_info['cover'], 'title' => $goods_info['title'], 'specification_name' => '默认', 'price' => $goods_info['price'], 'count' => $cart_info['goods_num']]],
            'discounts' => [
                'enable' => !empty($discounts),
                'lists' => $discounts
            ],
            'amounts'=>[
                'goods_amount'=> $goods_amount,
                'express_amount'=> $express_amount,
                'discount_amount' => $discount_amount,
                'pay_amount'=> (float)bcadd((string)$express_amount, bcsub((string)$goods_amount, (string)$discount_amount, 2), 2),
            ]
        ];
        //显示数据
        return showSuccess($data);
    }
}